 // ----------------------心跳代码开始-----------------------------

 const webSocketUrl = "'ws://14.18.190.138:48888/ws?sn=01'";
 const okhttp3 = Packages.okhttp3;
 const TimeUnit = java.util.concurrent.TimeUnit;
let ws = null;

 log("开始运行");
 events.on("exit", function () {
     log("结束运行");
     ws.close(1000, "再见");
     log("websocket关闭连接");
 });

 if (device.getBrightnessMode() == 1) {
     device.setBrightnessMode(0);

 }
 let totalBrihtness = 0;
 let BrightnessPercentage = 0;
 // 心跳
 heartConn = setInterval(() => {
    console.log("正在心跳...");
 }, 20000);

 let Listener = new okhttp3.WebSocketListener({
     onOpen: function (webSocket, response) {
         // 把websocket赋值给ws，方便后续心跳操作，ws是全局变量。
         ws = webSocket;
         let clientMsg = "客户端：连接成功";
         webSocket.send(clientMsg);
     },

     onMessage: function (webSocket, text) {
         log("onMessage: " + text);
         // 这里接收任务信息
         main(text);
     },

     onClosing: function (webSocket, code, reason) {
         4
         webSocket.close(1000, null);
         log("onClosing");
     },

     onClosed: function (webSocket, code, reason) {
         log("onClosed");
     },

     onFailure: function (webSocket, t, response) {
         log("onFailure: " + t.getMessage());
         clearInterval(heartConn);
         log("停止心跳");
     },
 });

 // 跟服务端websocket进行连接。
 var request = new okhttp3.Request.Builder().url(webSocketUrl).build();

 var client = new okhttp3.OkHttpClient.Builder()
     .readTimeout(3, TimeUnit.SECONDS) //设置读取超时时间
     .writeTimeout(3, TimeUnit.SECONDS) //设置写的超时时间
     .connectTimeout(3, TimeUnit.SECONDS) //设置连接超时时间
     .build();

 log("newWebSocket 开始");
 client.newWebSocket(request, Listener);
 log("newWebSocket 结束");

 log("调度 开始");
 client.dispatcher().executorService().shutdown();
 log("调度 结束");

 // ----------------------心跳代码结束-----------------------------